//首次运行本插件
if (!localStorage.isInitialized) {
	//是否接收桌面提醒
	localStorage.isActivated = true;
	//是否安装
	localStorage.isInitialized = true;
	//服务器地址
	localStorage.server = 'localhost:8098';
	//断线检测频率(默认15分钟)
	localStorage.frequency = 90000;
	var notification = webkitNotifications.createNotification(
		'images/ico.png',
		'提醒您：',
		'安装好了，亲~'
		);
	notification.show();
	setTimeout(function(){
		notification.cancel();
	},5000);
}

function checksvn(){
	//通过Websocket检测是否有新消息
	if('true' == localStorage.isActivated || true == localStorage.isActivated){
		var isActivated = true;
	}else{
		var isActivated = false;
	}
	var conn = new ab.Session(
		'ws://' + localStorage.server,
		function() {
			//Once the connection has been established
			var notification = webkitNotifications.createNotification(
				'images/ico.png',
				'提醒您：',
				"Websocket已经连接，SVN监控中！"
				);
			notification.show();
			setTimeout(function(){
				notification.cancel();
			},5000);
			//console.log(localStorage.frequency);
			//console.warn('WebSocket已经连接');
			conn.subscribe('SVN information', function(topic, data) {
				//console.log(data);
				var str = '';

				$.each(data.logentry,function(key,val){
					str = str + val['author'] + ' 在 ' + val['date'] + ' 提交了版本 ' + val['@attributes']['revision'] + '。' + "\n";
					str = str + '备注为：' + val['msg'] + "\n";
					var count = 0;
					$.each(val['paths']['path'],function(i,p){
						count = count + val['paths']['count'][i];
					//str = str + p + ' [' + val['paths']['count'][i] + ']' + "\n";
					});
					str = str + '本次提交了' + val['paths']['path'].length + '个文件，共计' + count + '行代码。' + "\n";
				});

				if(isActivated){
					var notification = webkitNotifications.createNotification(
						'images/ico.png',
						'SVN有更新：',
						str
						);
					notification.show();
					setTimeout(function(){
						notification.cancel();
					},30000);
				}
			});
		},
		function() {
			if(isActivated){
				var notification = webkitNotifications.createNotification(
					'images/ico.png',
					'提醒您：',
					'Websocket连接已经关闭！'
					);
				notification.show();
				setTimeout(function(){
					notification.cancel();
				},5000);
			}
			//console.warn('WebSocket连接已关闭');
			//如果掉线，15分钟后自动重新连接
			setTimeout(function(){
				checksvn();
			},localStorage.frequency ? localStorage.frequency : 90000);
		},
		{
			// Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
			'skipSubprotocolCheck': true
		}
		);
}

checksvn();